package com.tp.service;

import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tp.base.BaseService;
import com.tp.base.Paginator;
import com.tp.model.sys.SysMenu;
import com.tp.model.sys.SysRole;
import com.tp.model.sys.SysRoleMenu;
import com.tp.model.sys.SysUserRole;
import com.tp.utils.DateUtils;
import com.tp.utils.SQLUtils;
import com.tp.utils.StrUtils;
import javolution.util.FastList;
import javolution.util.FastMap;

/**
 * 角色service
 * 
 * @author TP
 *
 */
public class RoleService extends BaseService {

	private static SysRole sr = new SysRole().dao();
	private static SysUserRole sur = new SysUserRole().dao();
	private static SysRoleMenu srm = new SysRoleMenu().dao();

	/**
	 * 分页查询
	 * 
	 * @param model
	 * @param orderBy
	 * @param paginator
	 * @return
	 */
	public Page<SysRole> getPageByWhere(SysRole model, String orderBy, Paginator paginator) {
		SQLUtils sql = new SQLUtils("from " + SysRole.tableName + " t where 1=1");
		if (model.getAttrValues().length != 0) {
			sql.setAlias("t");
			// 查询条件
			sql.whereLike("name", model.getStr("name"));
		}
		if (StrUtils.isEmpty(orderBy)) {
			sql.append(" order by t.sort, t.id desc");
		} else {
			sql.append(" order by ").append(orderBy);
		}
		String sqlSelect = "select t.*, (select group_concat(m.name) from " + SysRoleMenu.tableName + " rm left join "
				+ SysMenu.tableName + " m on rm.menu_id = m.id where rm.role_id = t.id) as menus";
		Page<SysRole> page = sr.paginate(paginator, sqlSelect, sql.toString());
		return page;
	}

	/**
	 * 删除角色
	 * 
	 * @param ids
	 * @param uid
	 * @return
	 */
	public boolean deleteObject(String[] ids, Integer uid) {
		if (!StrUtils.empty(ids)) {
			boolean flag = false;
			for (String id : ids) {
				// 删除授权菜单
				Db.update("delete from " + SysRoleMenu.tableName + " where role_id=?", id);
				// 删除授权角色
				Db.update("delete from " + SysUserRole.tableName + " where role_id=?", id);
				SysRole model = new SysRole();
				model.put("update_id", uid);
				model.put("update_time", DateUtils.getNow(DateUtils.DEFAULT_REGEX_YYYY_MM_DD_HH_MIN_SS));
				flag = model.deleteById(id);
				if (!flag) {
					break;
				}
			}
			return flag;
		}
		return false;
	}

	/**
	 * 根据状态查询角色
	 * 
	 * @param status
	 * @return
	 */
	public String getRoleList(int status) {
		List<SysRole> list = sr.findByWhere("where status = ? order by sort", status);
		List<Map<String, Object>> listMap = FastList.newInstance();
		for (SysRole itme : list) {
			Map<String, Object> temp = FastMap.newInstance();
			temp.put("value", itme.getStr("id"));
			temp.put("title", itme.getName());
			listMap.add(temp);
		}
		return JSON.toJSONString(listMap);
	}

	/**
	 * 查询用户角色ID
	 * 
	 * @param uid
	 * @return
	 */
	public String getUserRoleId(int uid) {
		String roleIds = "[]";
		SysUserRole ur = sur.findFirst("select group_concat(role_id) as rIds from sys_user_role where user_id = ?", uid);
		if (!StrUtils.empty(ur.get("rIds"))) {
			roleIds = ur.getStr("rIds");
		}
		return roleIds;
	}
	
	/**
	 * 查询角色菜单权限
	 * @param rId
	 * @return
	 */
	public String getRoleMenu(int rId){
		String menuIds = "";
		SysRoleMenu rm = srm.findFirst("select group_concat(menu_id) as mIds from sys_role_menu where role_id=?", rId);
		if(!StrUtils.empty(rm.get("mIds"))){
			menuIds = rm.getStr("mIds");
		}
		return menuIds;
	}

	/**
	 * 保存角色菜单权限
	 * 
	 * @param roleid
	 * @param menus
	 * @param update_id
	 * @return
	 */
	public boolean saveRoleAuth(Integer roleid, String mIds, int update_id) {
		boolean flag = false;
		// 删除原有数据库
		Db.update("delete from " + SysRoleMenu.tableName + " where role_id=?", roleid);
		if (!StrUtils.empty(mIds)) {
			String[] arry = mIds.split(",");
			for (String mid : arry) {
				SysRoleMenu roleMenu = new SysRoleMenu();
				roleMenu.setRoleId(roleid);
				roleMenu.setMenuId(Integer.valueOf(mid));
				// 日志添加
				roleMenu.put("update_id", update_id);
				roleMenu.put("update_time", DateUtils.getNow(DateUtils.DEFAULT_REGEX_YYYY_MM_DD_HH_MIN_SS));
				flag = roleMenu.save();
			}
		} else {
			flag = true;
		}
		return flag;
	}
}
